package com.silence.gankio.mvvm.view

import android.os.Bundle
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.KeyEvent
import com.alibaba.android.arouter.facade.annotation.Route
import com.silence.gankio.App
import com.silence.gankio.R
import com.silence.gankio.adapter.MainFragmentAdapter
import com.silence.gankio.config.Constance
import com.silence.gankio.mvvm.BaseActivity
import com.silence.gankio.mvvm.viewModel.MainViewModel
import com.silence.gankio.util.ToastUtil
import kotlinx.android.synthetic.main.activity_main_binding.*

@Route(path = Constance.ACTIVITY_URL_MAIN_BINGING)
class MainActivity : BaseActivity<MainViewModel>() {

    override fun getActivityContent() = R.layout.activity_main_binding

    override fun getModelClass(): Class<MainViewModel>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView()
        if (null == savedInstanceState) {
            initFragment()
        }
        setToolBarTitle("主页")
    }

    private fun initFragment() {
    }

    private fun initView() {
        //设置返回键可用
        supportActionBar?.setHomeButtonEnabled(true)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        val toggle =
            ActionBarDrawerToggle(this, drawer, mToolbar, R.string.home_drawer_open, R.string.home_drawer_close)
        toggle.syncState()
        drawer.addDrawerListener(toggle)

        //设置图片为本身的颜色
        nav.itemIconTintList = null
        //设置item的点击事件
        nav.setNavigationItemSelectedListener {
            drawer.closeDrawer(GravityCompat.START)
            when (it.itemId) {
                R.id.bluetooth -> {
//                    startActivity<BluetoothActivity>()
                    getRouter(Constance.ACTIVITY_URL_BLUETOOTH)
                        .navigation()
                }
                else -> {
                }
            }
            return@setNavigationItemSelectedListener true
        }

        view_pager.adapter = MainFragmentAdapter(supportFragmentManager)
        tabs.setupWithViewPager(view_pager)
        view_pager.currentItem = 0
        view_pager.offscreenPageLimit = 3

    }

    private var mExitTime: Long = 0L

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (supportFragmentManager.backStackEntryCount != 0) {
                supportFragmentManager.popBackStack()
            } else {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    ToastUtil.showToast(this, "再按一次退出", ToastUtil.ToastyType.WARNING)
                    mExitTime = System.currentTimeMillis()
                } else {
                    App().exit()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}
